<template>
  <div class="contracts-page">
    <div class="card">
      <div class="table-toolbar">
        <div class="toolbar-left">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增合同
          </el-button>
          <el-button type="success" @click="handleTemplate">
            <el-icon><Document /></el-icon>
            合同模板
          </el-button>
          <el-button type="danger" :disabled="!selectedIds.length" @click="handleBatchDelete">
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
        </div>
        <div class="toolbar-right">
          <el-select
            v-model="searchForm.status"
            placeholder="合同状态"
            clearable
            style="width: 120px; margin-right: 10px"
            @change="handleSearch"
          >
            <el-option label="草稿" value="draft" />
            <el-option label="审核中" value="reviewing" />
            <el-option label="已批准" value="approved" />
            <el-option label="已签署" value="signed" />
            <el-option label="已过期" value="expired" />
          </el-select>
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索合同标题、编号"
            style="width: 200px"
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button @click="handleSearch">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        stripe
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="contractNumber" label="合同编号" width="140" />
        <el-table-column prop="title" label="合同标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="type" label="合同类型" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="clientName" label="客户" width="120" />
        <el-table-column prop="amount" label="合同金额" width="120">
          <template #default="{ row }">
            {{ formatMoney(row.amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="signDate" label="签署日期" width="120">
          <template #default="{ row }">
            {{ row.signDate ? formatDate(row.signDate, 'YYYY-MM-DD') : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="startDate" label="开始日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.startDate, 'YYYY-MM-DD') }}
          </template>
        </el-table-column>
        <el-table-column prop="endDate" label="结束日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.endDate, 'YYYY-MM-DD') }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
            <el-button type="success" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 合同表单对话框 -->
    <ContractForm
      v-model:visible="formVisible"
      :form-data="formData"
      @success="handleFormSuccess"
    />

    <!-- 合同模板对话框 -->
    <TemplateDialog
      v-model:visible="templateVisible"
      @success="handleTemplateSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getContractList, deleteContract } from '@/api/contract'
import { formatDate, formatMoney } from '@/utils'
import type { Contract, Pagination } from '@/types'
import ContractForm from './components/ContractForm.vue'
import TemplateDialog from './components/TemplateDialog.vue'

const router = useRouter()
const loading = ref(false)
const selectedIds = ref<string[]>([])
const tableData = ref<Contract[]>([])
const formVisible = ref(false)
const templateVisible = ref(false)
const formData = ref<Partial<Contract>>({})

const searchForm = reactive({
  keyword: '',
  status: ''
})

const pagination = reactive<Pagination>({
  current: 1,
  pageSize: 20,
  total: 0
})

// 获取合同列表
const fetchContractList = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.current,
      size: pagination.pageSize,
      ...searchForm
    }
    const data = await getContractList(params)
    tableData.value = data.list
    pagination.total = data.total
  } catch (error) {
    ElMessage.error('获取合同列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchContractList()
}

// 选择变化
const handleSelectionChange = (selection: Contract[]) => {
  selectedIds.value = selection.map(item => item.id)
}

// 新增合同
const handleAdd = () => {
  formData.value = {}
  formVisible.value = true
}

// 合同模板
const handleTemplate = () => {
  templateVisible.value = true
}

// 查看合同
const handleView = (row: Contract) => {
  router.push(`/contracts/detail/${row.id}`)
}

// 编辑合同
const handleEdit = (row: Contract) => {
  formData.value = { ...row }
  formVisible.value = true
}

// 删除合同
const handleDelete = async (row: Contract) => {
  try {
    await ElMessageBox.confirm(`确定要删除合同 "${row.title}" 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteContract(row.id)
    ElMessage.success('删除成功')
    fetchContractList()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.value.length} 个合同吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await Promise.all(selectedIds.value.map(id => deleteContract(id)))
    ElMessage.success('批量删除成功')
    fetchContractList()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

// 表单提交成功
const handleFormSuccess = () => {
  fetchContractList()
}

// 模板操作成功
const handleTemplateSuccess = () => {
  // 可以刷新模板列表或其他操作
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.current = 1
  fetchContractList()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.current = page
  fetchContractList()
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    draft: 'info',
    reviewing: 'warning',
    approved: 'primary',
    signed: 'success',
    expired: 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    draft: '草稿',
    reviewing: '审核中',
    approved: '已批准',
    signed: '已签署',
    expired: '已过期'
  }
  return textMap[status] || status
}

onMounted(() => {
  fetchContractList()
})
</script>

<style lang="scss" scoped>
.contracts-page {
  .pagination {
    margin-top: 20px;
    text-align: right;
  }
}
</style>
